//
//  WKRefreshControl.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/14.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
private let WKRefreshControlOffset: CGFloat = -60
class WKRefreshControl: UIRefreshControl {
    
    //停止刷新
    override func endRefreshing() {
        
        super.endRefreshing()
        refreshView.stopAnimation()
        
    }
    
    //主动开始刷新
    override func beginRefreshing() {
        
        super.beginRefreshing()
        refreshView.startAnimation()
        
    }
    
    //利用KVO监听属性的变化
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
        
            return
        }
        
        //判断是否在刷新
        if refreshing{
        
            //开始动画
            refreshView.startAnimation()
        
        }
        
        if frame.origin.y < WKRefreshControlOffset && !refreshView.rotateFlag {
            print("反过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y >= WKRefreshControlOffset && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
        
    }
    
    
    //构造函数
    override init() {
        
        super.init()
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder: aDecoder)
        
        setUpUI()
    }
    
    
    
    //更新UI
    private func setUpUI(){
    
        //添加控件
        addSubview(refreshView)
        
        //设置刷新控件颜色
        tintColor = UIColor.clearColor()
        
        //设置自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
            
        }
        
        //监听属性的变化
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
            
        }
    
    }
    
    //移除监听
    deinit{
    
        self.removeObserver(self, forKeyPath: "frame")
    
    }
    
    /// 懒加载控件
    private lazy var refreshView = WKRefreshView.refreshView()
}

class WKRefreshView: UIView {

    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipIconView: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    //旋转标记
    var rotateFlag = false{
    
        didSet{
        
            rotateTipTcon()
        
        }
    
    }
    
    
        //从XIB加载视图
    class func refreshView() ->WKRefreshView {
    
        let nib = UINib(nibName: "WKRefreshView", bundle: nil)
    
        return nib.instantiateWithOwner(nib, options: nil).first as! WKRefreshView
    }

    //旋转图片的动画
    private func rotateTipTcon(){
    
        var angle = CGFloat(M_PI)
        
        angle += rotateFlag ? -0.0000001 : 0.0000001
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            //进行动画旋转
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, CGFloat(angle))
            
            
        }
        
        
    }
    
    //播放加载动画
    private func startAnimation(){
    
        tipView.hidden = true
        
        //判断动画是否添加
        let key = "transform.rotation"
        
        if loadingIconView.layer.animationForKey(key) != nil {
        
            return
        }
    
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        
        anim.repeatCount = MAXFLOAT
        
        anim.duration = 0.5
        
        anim.removedOnCompletion = false
        
        //添加动画
        loadingIconView.layer.addAnimation(anim, forKey: key)
    }
    
    
    //停止动画
    private func stopAnimation(){
    
        tipView.hidden = false
        
        loadingIconView.layer.removeAllAnimations()
    
    }

}